<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace App\Exception\Handler;

use App\BaseResponse;
use App\Cache\CacheKey;
use App\Enum\Code;
use App\Exception\BusinessException;
use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Hyperf\Redis\Redis;
use Hyperf\Validation\ValidationException;
use Psr\Http\Message\ResponseInterface;
use Throwable;

class AppExceptionHandler extends ExceptionHandler
{
    /**
     * @var StdoutLoggerInterface
     */
    protected $logger;

    public function __construct(StdoutLoggerInterface $logger, private Redis $redis)
    {
        $this->logger = $logger;
    }

    public function handle(Throwable $throwable, ResponseInterface $response)
    {
        $this->logger->error(sprintf('%s[%s] in %s', $throwable->getMessage(), $throwable->getLine(), $throwable->getFile()));
        $this->logger->error($throwable->getTraceAsString());

        // 记录异常数量
        $this->redis->zAdd(CacheKey::exceptionCountMinute(), time(), uniqid('', true));

        if ($throwable instanceof BusinessException) {
            return $response->withStatus($throwable->errCode->getHttpCode())
                ->withBody(new SwooleStream((string) new BaseResponse($throwable->errCode, $throwable->getMessage(), $throwable->data)));
        } elseif ($throwable instanceof ValidationException) {
            return $response->withStatus(Code::RequestParamError->getHttpCode())
                ->withBody(new SwooleStream((string) new BaseResponse(
                    Code::RequestParamError,
                    '参数验证错误',
                    $throwable->validator->errors()
                )));
        } else {
            if (is_production()) {
                return $response->withStatus(Code::InternalServerError->getHttpCode())
                    ->withBody(new SwooleStream((string) new BaseResponse(
                        Code::InternalServerError,
                        '服务器错误，请稍后再试',
                        []
                    )));
            } else {
                return $response->withStatus(Code::InternalServerError->getHttpCode())
                    ->withBody(new SwooleStream((string)new BaseResponse(Code::InternalServerError, $throwable->getMessage(), $throwable->getTrace())));
            }
        }

//        return $response->withHeader('Server', 'Hyperf')->withStatus(500)->withBody(new SwooleStream('Internal Server Error.'));
    }

    public function isValid(Throwable $throwable): bool
    {
        return true;
    }
}
